﻿namespace SimpleX
{
    public class RealIPMiddleware
    {
        private readonly RequestDelegate _next;

        public RealIPMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            var headers = context.Request.Headers;
            try
            {
                if (headers.ContainsKey("X-Real-IP"))
                {
                    if (headers.ContainsKey("X-Forwarded-For"))
                        context.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Forwarded-For"].ToString().Split(',')[0]);
                    else
                        context.Connection.RemoteIpAddress = IPAddress.Parse(headers["X-Real-IP"].ToString());
                }
            }
            finally
            {
                await _next(context);
            }
        }
    }
}